package org.makabaka.wfwwb.controller;

import cn.hutool.core.util.StrUtil;
import org.makabaka.wfwwb.common.ServiceException;
import org.makabaka.wfwwb.pojo.Result;
import org.makabaka.wfwwb.pojo.Token;
import org.makabaka.wfwwb.pojo.User;
import org.makabaka.wfwwb.service.UserService;
import org.makabaka.wfwwb.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")

public class UserController {
    @Autowired
    private UserService userService;


    @GetMapping("/getAllUsers")
    public Result getAllUsers() {
        return Result.success(userService.getAllUsers());
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        if (StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPassword())) {
            throw new ServiceException("401", "登录失败: 请输入用户名和密码");
        }
        User quser = userService.login(user);
        return Result.success(quser);
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        if (StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPassword())) {
            throw new ServiceException("401", "注册失败: 请输入用户名和密码");
        }
        int q = userService.register(user);
        if (q == 1) {
            return Result.success(null);
        }
        return Result.error("401", "注册失败: 请联系玛卡巴卡");
    }

    @PostMapping("/verifyToken")

    public Result verifyToken(@RequestBody Token tokenObj) {
        String token = tokenObj.getToken();
        if (StrUtil.isBlank(token)) {
            return Result.error("401", "验证失败: 缺少token");
        }
        if (UserUtil.verifyToken(token)) {
            return Result.success(null);
        }
        return Result.error("401", "验证失败: token错误");
    }

    @PostMapping("/getUserInfo")
    public Result getUserInfo(@RequestBody Token tokenObj) {
        String token = tokenObj.getToken();
        if (StrUtil.isBlank(token)) {
            return Result.error("401", "获取用户信息失败: 缺少token");
        }
        if (!UserUtil.verifyToken(token)) {
            return Result.error("401", "获取用户信息失败: token错误");
        }
        User quser = userService.getUserInfo(token);
        if (quser == null) {
            return Result.error("401", "获取用户信息失败: 用户不存在");
        }
        return Result.success(quser);
    }


}
